package com.qfedu.fmmall.orderAdd.service.impl;

import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.orderAdd.dao.OrdersDao;
import com.qfedu.fmmall.orderAdd.service.OrderAddService;
import com.qfedu.fmmall.orderAdd.service.feign.StockQueryClient;
import com.qfedu.fmmall.vo.ShoppingCartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author : yanBin
 * @date :2022/2/10 14:27
 */
@Service
public class OrderAddServiceImpl implements OrderAddService {
    private static final Logger log = LoggerFactory.getLogger(OrderAddServiceImpl.class);

    @Autowired
    private StockQueryClient stockQueryClient;

    @Autowired
    private OrdersDao ordersDao;

    @Override
    public List<ShoppingCartVO> saveOrder(Orders orders, String cids) {
        try {
            //查询购物车记录
            List<ShoppingCartVO> shoppingCartVOList = stockQueryClient.query(cids);
            if (CollectionUtils.isEmpty(shoppingCartVOList)) {
                return null;
            }

            //判断购物车所购商品是否有库存
            Boolean f = true;
            StringBuffer untitled = new StringBuffer();
            for (ShoppingCartVO sc : shoppingCartVOList) {
                if (Integer.valueOf(sc.getCartNum()) > sc.getSkuStock()) {
                    f = false;
                    break;
                }
                untitled.append(sc.getProductName());
                untitled.append(",");

            }
            if (!f) {
                return null;
            }
            //添加到订单表orders
            orders.setUntitled(untitled.toString());
            orders.setCancelTime(new Date());
            orders.setStatus("1");

//            String orderId = UUID.randomUUID().toString().replace("-", "");
//            orders.setOrderId(orderId);

            int i = ordersDao.insertSelective(orders);
            if (i <= 0) {
                return null;
            }
            return shoppingCartVOList;
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return null;
        }

    }
}
